/**
 * @Description 获取电脑中所盘符及其名称
 * @Author
 * @Date
 */
const process = require("child_process");
var iconv = require("iconv-lite");
const os = require("os");
// cmd命令
const cmdOrder = {
  getAllDrive: () => "wmic logicaldisk where drivetype=2 get deviceid",
  getOneDriveName: (drive) =>
    `wmic logicaldisk where name="${drive}:" get volumename`,
};

/**
 * 获取电脑中所有盘符及其名称
 * @returns 电脑中所有盘符及其名称
 */
async function getAllDrive() {
  let result = [];
  const system = os.platform();
  if (system === "linux") {
    console.log('linux')
  } else {
    console.log('是windows')
    let promise = new Promise((resolve, reject) => {
      // 获取电脑中所有盘符
      process.exec(cmdOrder.getAllDrive(), (error, stdout) => {
        if (error !== null) {
          console.error(error);
          return;
        }
        let stdoutArr = [...stdout];
        let res = [];
        stdoutArr.forEach((v, i) => {
          if (v === ":") {
            res.push(stdoutArr[i - 1]);
          }
        });

        let resList = [];
        let promiseArr = [];
        // 获取所有盘符的所有名称
        res.forEach((v) => {
          promiseArr.push(
            new Promise((resolve, reject) => {
              process.exec(
                cmdOrder.getOneDriveName(v),
                { encoding: "buffer" },
                (error, stdout) => {
                  if (error !== null) {
                    console.error(error);
                    return;
                  }
                  let stdoutArr = [...iconv.decode(stdout, "cp936")];
                  let res = [];
                  stdoutArr.forEach((v, i) => {
                    if (v !== " " && v !== "\n" && v !== "\r") {
                      res.push(v);
                    }
                  });
                  res.splice(0, 10);
                  resList.push({
                    drive: v,
                    name: res.join(""),
                    id: Math.ceil(Math.random() * 100000000),
                  });
                  resolve(true);
                }
              );
            })
          );
        });
        Promise.all(promiseArr).then((res) => {
          resolve(resList);
        });
      });
    });
    await promise.then((resy) => {
      result = resy;
    });
  }

  return result;
}

module.exports = getAllDrive;
